import os
from concurrent import futures
import sys
import requests
import time

MAX_WORKERS = 20  # <1>最大线程数
POP20_CC = ["pms_1508850965.67096774",
            "pms_1509723338.05097112",
            "pms_1508125822.19716710",
            "pms_1512614327.2483640",
            "pms_1525853341.8312102"]

BASE_URL = 'https://i1.mifile.cn/a1'

DEST_DIR = 'files'


def save_flag(img, filename):
    path = os.path.join(DEST_DIR, filename)
    with open(path, 'wb') as fp:
        fp.write(img)


def get_flag(cc):
    url = '{}/{cc}.jpg'.format(BASE_URL, cc=cc.lower())
    resp = requests.get(url)
    return resp.content


def download_one(cc):
    image = get_flag(cc)
    sys.stdout.flush()
    save_flag(image, cc.lower() + '.jpg')
    return cc


def download_many(cc_list):  # <2>多线程同时下载图片，这里活跃线程数为5，即5张图片
    workers = min(MAX_WORKERS, len(cc_list))
    with futures.ThreadPoolExecutor(workers) as executor:
        res = executor.map(download_one, sorted(cc_list))
    return len(list(res))


def main():
    directory = os.path.join(DEST_DIR)
    if not os.path.exists(directory):
        os.mkdir(directory)
    t0 = time.time()
    count = download_many(POP20_CC)
    elapsed = time.time() - t0
    msg = '\n{} flags downloaded in {:.2f}s'
    print(msg.format(count, elapsed))


if __name__ == '__main__':
    main()
